package com.stx.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stx.exception.CustomException;
import com.stx.exception.CustomExceptionUtils;
import com.stx.mapper.JudgeMapper;
import com.stx.mapper.PlayerMapper;
import com.stx.pojo.Judge;
import com.stx.pojo.Player;
import com.stx.pojo.Record;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PlayerService extends ServiceImpl<PlayerMapper, Player> {

    @Autowired
    private PlayerMapper playerMapper;

    public List<Player> getplayer() {
        return playerMapper.selectplayer();
    }

    public void add(Player player) {
        //1.用户名一定要有，否则不让新增（后面需要用户名登录）
        if(player.getPlaName() == null || "".equals(player.getPlaName())) {
            throw new CustomExceptionUtils("用户名不能为空");
        }
        //2.进行重复性判断，同一名字的管理员不允许重复新增
        //只要根据用户名去数据查询一下就可以
        Player user = playerMapper.findByName(player.getPlaName());
        if(user != null) {
            //说明已经有了，这里我们就要提示前台不允许新增了
            throw new CustomExceptionUtils("该用户名已存在，请勿重复添加");
        }

        if(player.getPlaDate() == null) {
            player.setPlaDate(LocalDateTime.now());
        }
        playerMapper.add(player);
    }

    public void update(Player player) {
        player.setPlaDate(LocalDateTime.now());
        playerMapper.updateID(player);
    }

    public void delete(Integer id) {
        playerMapper.deleteID(id);
    }

    public Page<Player> find(Object plaName, Object department, Integer currentPage, Integer pageSize) {
        System.out.println("name=" + plaName);
        LambdaQueryWrapper<Player> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(plaName!=null, Player::getPlaName, plaName);
        wrapper.like(department!=null, Player::getPlaDepartment, department);
        //创建分页条件
        Page<Player> page = new Page<>(currentPage, pageSize);
        //执行分页查询（分页结果）
        Page<Player> resultPage = playerMapper.selectPage(page, wrapper);
        //当前页数据
        List<Player> records = resultPage.getRecords();
        //总记录数
        long total = resultPage.getTotal();
        //总页数
        long pages = resultPage.getPages();
        com.stx.common.Page<Record> pageFind = new com.stx.common.Page<>();
        pageFind.setTotal(total);
        pageFind.setPages(pages);
        return page;
    }
}
